package com.lanlian.cayman.rabbitmq;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/20 15:14
 *     desc   : MQ管理类
 *     version: 1.0
 * </pre>
 */
public class MQFactory {

    private static final String TAG = "MQFactory";

    private static MQFactory singleton;

    private String hostName;
    private int port;
    private String username;
    private String password;

    private ExecutorService executor;

    private ArrayList<MQConsumer> mMQConsumers = new ArrayList<>();

    public void init(String hostName, int port, String username, String password) {
        this.hostName = hostName;
        this.port = port;
        this.username = username;
        this.password = password;
        this.executor = Executors.newFixedThreadPool(5);
    }

    public static MQFactory getInstance() {
        if (singleton == null) {
            synchronized (MQFactory.class) {
                if (singleton == null) {
                    singleton = new MQFactory();
                }
            }
        }
        return singleton;
    }

    public boolean close() {
        for (MQConsumer mMQConsumer : mMQConsumers) {
            mMQConsumer.close();
        }
        mMQConsumers.clear();
        executor.shutdown();
        return true;
    }

    public void removeConsumer(MQConsumer mqConsumer) {
        mMQConsumers.remove(mqConsumer);
    }

    public MQConsumer createConsumer(MQCallback callback, String exchange, String routingKey) {
        MQConsumer mqConsumer = MQConsumer.createInstance(this, callback, exchange, routingKey);
        mMQConsumers.add(mqConsumer);
        return mqConsumer;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public ExecutorService getExecutor() {
        return executor;
    }

    public void setExecutor(ExecutorService executor) {
        this.executor = executor;
    }
}
